package com.ivy.irublesson.activity;


import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ivy.irublesson.R;
import com.ivy.irublesson.entity.School;
import com.ivy.irublesson.entity.Teacher;
import com.ivy.irublesson.fragment.CourseFragment;
import com.ivy.irublesson.fragment.SecondFragment;
import com.ivy.irublesson.fragment.TeacherFragment;
import com.ivy.irublesson.utils.HttpUtil;
import com.ivy.irublesson.utils.MyOpenHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class InitActivity extends AppCompatActivity implements View.OnClickListener{
    // 底部菜单3个Linearlayout
    private LinearLayout ll_home;
    private LinearLayout ll_address;
    private LinearLayout ll_friend;

    // 底部菜单3个ImageView
    private ImageView iv_home;
    private ImageView iv_address;
    private ImageView iv_friend;

    // 底部菜单3个菜单标题
    private TextView tv_home;
    private TextView tv_address;
    private TextView tv_friend;

    // 3个Fragment
    private CourseFragment courseFragment;
    private SecondFragment secondFragment;
    private TeacherFragment teacherFragment;


    private Spinner sp;
    private List<String> list;
    private List<School> schools  = new ArrayList<>();
    private Handler handler;
    private MyOpenHelper openHelper;


//    private FragmentManager fragmentManager = getSupportFragmentManager();
//    // 开启事务
//    private FragmentTransaction transaction = fragmentManager.beginTransaction();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化  查询数据库的学校信息
//        openHelper = new MyOpenHelper(this, "irublesson.db", null, 1);
//        SQLiteDatabase database = openHelper.getReadableDatabase();
//        String sql = "select * from school";
//        Cursor cursor = database.rawQuery(sql, null);	//	若是有问号，传入参数数组   否则为null；
//        while(cursor.moveToNext()) {
//            School school = new School();
//            school.setId(cursor.getInt(cursor.getColumnIndex("id")));
//            school.setSname(cursor.getString(cursor.getColumnIndex("sname")));
//            school.setListpath(cursor.getString(cursor.getColumnIndex("listpath")));
//            school.setListcookie(cursor.getString(cursor.getColumnIndex("listcookie")));
//            school.setReferer(cursor.getString(cursor.getColumnIndex("referer")));
//            school.setCookiepath(cursor.getString(cursor.getColumnIndex("cookiepath")));
//            school.setCoursepath(cursor.getString(cursor.getColumnIndex("coursepath")));
//            Log.i("=========schoolname---" ,school.getSname());
//            schools.add(school);
//        }




        Thread schoolThread = new Thread(new SchoolThread());
        schoolThread.start();
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //下拉栏
        list = new ArrayList<String>();
        for(School school : schools){
            list.add(school.getSname());
            Log.i("schoolname---" ,school.getSname());
        }
        sp = (Spinner) findViewById(R.id.csp);
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(InitActivity.this,adapter.getItem(position),Toast.LENGTH_SHORT).show();
                School school = schools.get(position);
//                Bundle bundle = new Bundle();
//                int sid = school.getId();
//                bundle.putInt("sid", sid);
//                teacherFragment.setArguments(bundle);
//                //如果transaction  commit（）过  那么我们要重新得到transaction
//                transaction = fragmentManager.beginTransaction();
//                transaction.replace(R.id.fl_content, teacherFragment);
//                transaction.commit();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        // 初始化控件
        initView();
        // 初始化底部按钮事件
        initEvent();
        // 初始化并设置当前Fragment
        initFragment(1);

    }

    private String schoolPath = "http://119.23.232.105:8080/IRubLesson/SchoolServlet";
    class SchoolThread implements Runnable {
        @Override
        public void run() {
            try {
                JSONArray arr = HttpUtil.getJSONArrayByURL(schoolPath);
                for(int i = 0;i < arr.length();i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    School school = new School();
                    school.setId(obj.getInt("id"));
                    school.setSname(obj.getString("sname"));
                    school.setListpath(obj.getString("listpath"));
                    school.setListcookie(obj.getString("listcookie"));
                    school.setReferer(obj.getString("referer"));
                    school.setCookiepath(obj.getString("cookiepath"));
                    school.setCoursepath(obj.getString("coursepath"));
                    //  map.put("owner_tel", obj.getString("owner_tel"));
                    schools.add(school);

                }
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void initFragment(int index) {
        // 由于是引用了V4包下的Fragment，所以这里的管理器要用getSupportFragmentManager获取
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 开启事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 隐藏所有Fragment
        hideFragment(transaction);
        switch (index) {
            case 0:
                if (courseFragment == null) {
                    courseFragment = new CourseFragment(this);
                    transaction.add(R.id.fl_content, courseFragment);
                } else {
                    transaction.show(courseFragment);
                }
                break;
            case 1:
                if (teacherFragment == null) {
                    teacherFragment = new TeacherFragment(this);
//                    Bundle bundle = new Bundle();
//                    int sid = 1;
//                    bundle.putInt("sid", sid);
//                    teacherFragment.setArguments(bundle);
                    transaction.add(R.id.fl_content, teacherFragment);
                } else {
                    transaction.show(teacherFragment);
                }
                break;
            case 2:
                if (secondFragment == null) {
                    secondFragment = new SecondFragment();
                    transaction.add(R.id.fl_content, secondFragment);
                } else {
                    transaction.show(secondFragment);
                }
                break;

            default:
                break;
        }
        // 提交事务
        transaction.commit();
    }
    //隐藏Fragment
    private void hideFragment(FragmentTransaction transaction) {
        if (courseFragment != null) {
            transaction.hide(courseFragment);
        }
        if (secondFragment != null) {
            transaction.hide(secondFragment);
        }
        if (teacherFragment != null) {
            transaction.hide(teacherFragment);
        }

    }
    private void initEvent() {
        // 设置按钮监听
        ll_home.setOnClickListener(this);
        ll_address.setOnClickListener(this);
        ll_friend.setOnClickListener(this);
    }
    private void initView() {
        // 底部菜单3个Linearlayout
        this.ll_home = (LinearLayout) findViewById(R.id.ll_home);
        this.ll_address = (LinearLayout) findViewById(R.id.ll_address);
        this.ll_friend = (LinearLayout) findViewById(R.id.ll_friend);

        // 底部菜单3个ImageView
        this.iv_home = (ImageView) findViewById(R.id.iv_home);
        this.iv_address = (ImageView) findViewById(R.id.iv_address);
        this.iv_friend = (ImageView) findViewById(R.id.iv_friend);

        // 底部菜单3个菜单标题
        this.tv_home = (TextView) findViewById(R.id.tv_home);
        this.tv_address = (TextView) findViewById(R.id.tv_address);
        this.tv_friend = (TextView) findViewById(R.id.tv_friend);

    }
    @Override
    public void onClick(View v) {
        // 在每次点击后将所有的底部按钮(ImageView,TextView)颜色改为灰色，然后根据点击着色
        restartBotton();
        // ImageView和TetxView置为蓝色，页面随之跳转
        switch (v.getId()) {
            case R.id.ll_home:
                iv_home.setImageResource(R.drawable.wxb1);
                tv_home.setTextColor(Color.rgb(18,150,219));
                initFragment(0);
                break;
            case R.id.ll_address:
                iv_address.setImageResource(R.drawable.text1);
                tv_address.setTextColor(Color.rgb(18,150,219));
                initFragment(1);
                break;
            case R.id.ll_friend:
                iv_friend.setImageResource(R.drawable.account1);
                tv_friend.setTextColor(Color.rgb(18,150,219));
                initFragment(2);
                break;

            default:
                break;
        }
    }


    private void restartBotton() {
        // ImageView置为灰色
        iv_home.setImageResource(R.drawable.wxb);
        iv_address.setImageResource(R.drawable.text);
        iv_friend.setImageResource(R.drawable.account);

        // TextView置为灰色
        tv_home.setTextColor(Color.rgb(112,112,112));
        tv_address.setTextColor(Color.rgb(112,112,112));
        tv_friend.setTextColor(Color.rgb(112,112,112));

    }

}
